package com.shuo.juc.semaphore;

import java.util.concurrent.Semaphore;

/**
 * 信号量一般用于限制某个资源同时只能被n个线程访问
 */
@SuppressWarnings("Duplicates")
public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(3, true);
        new Thread(() -> {
            try {
                // 不阻塞
                semaphore.acquire();
                sleeping(5);
                semaphore.release();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                // 不阻塞
                semaphore.acquire();
                sleeping(6);
                semaphore.release();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                // 不阻塞
                semaphore.acquire();
                sleeping(6);
                semaphore.release();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                // 阻塞, 5s后才通
                semaphore.acquire();
                sleeping(5);
                semaphore.release();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void sleeping(int sec) {
        try {
            Thread.sleep(sec * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
